package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.security.auth.login.LoginException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {


    @Autowired
    private UserService userService;

    @Autowired
    private VMService vmService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private MqttProducer mqttProducer;


    /**
     * 新增工单
     *
     * @param taskViewModel
     * @return
     */
    @Override
    @Transactional
    public boolean create(TaskViewModel taskViewModel) throws LogicException {
        //校验售货机状态
        checkVMStatus(taskViewModel);
        //检验同一台设备是否有未完成工单
        checkTask(taskViewModel);

        //1.创建工单对象，属性拷贝
        TaskEntity taskEntity = new TaskEntity();
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        //使用redis生成工单编号：8位年月日+4位当日序号
        String taskCode = getTaskCode();
        taskEntity.setTaskCode(taskCode);
        //设置工单状态
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        //跨服务查询售货机微服务，设置所属区域id
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        taskEntity.setRegionId(vmInfo.getRegionId());
        //设置点位名称
        taskEntity.setAddr(vmInfo.getNodeName());
        //设置用户名称
        UserVO user = userService.getUser(taskViewModel.getUserId());
        taskEntity.setUserName(user.getUserName());
        //设置工单类型id
        taskEntity.setProductTypeId(taskViewModel.getProductType());

        //2.添加工单
        save(taskEntity);

        //3.如果是补货工单需要添加详情
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            List<TaskDetailsViewModel> details = taskViewModel.getDetails();
            details.forEach(t -> {
                TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(t, taskDetailsEntity);
                taskDetailsEntity.setTaskId(taskEntity.getTaskId());
                //添加详情
                taskDetailsService.save(taskDetailsEntity);
            });
        }

        //创建工单完成后，需要更新redis中的zset中接单数
        updateTaskZset(taskEntity, 1);

        return true;
    }

    /**
     * 更新redis中zset的接单数
     *
     * @param taskEntity
     * @param score
     */
    private void updateTaskZset(TaskEntity taskEntity, int score) {
        //根据工单类型判断身份
        String roleCode = "1003"; //默认是运维人员
        if (taskEntity.getProductTypeId().intValue() == VMSystem.TASK_TYPE_SUPPLY) {
            roleCode = "1002"; //如果工单类型是补货工单，则为运营人员
        }


        //key值 固定前缀+日期+区域+工单类别（运营+运维）
        String key = VMSystem.REGION_TASK_KEY_PREF +
                LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + taskEntity.getRegionId() + "." + roleCode;
        //修改接单数
        redisTemplate.opsForZSet().incrementScore(key, taskEntity.getUserId(), score);


    }

    /**
     * 接受工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean accept(Long id) {
        TaskEntity task = getById(id);

        //判断订单状态，不是待处理则抛出异常
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE) {
            throw new LogicException("工单状态不是未处理");
        }

        //修改工单状态为进行中
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        return updateById(task);
    }

    /**
     * 拒绝/取消工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean cancel(Long id, CancelTaskViewModel cancelTaskViewModel) {
        TaskEntity task = getById(id);
        //1.判断工单状态是否为已取消或者已完成，是则抛出异常
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL || task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH) {
            throw new LogicException("工单状态为已取消或已完成");
        }

        //2.修改工单状态为取消，同时记录拒绝原因
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(cancelTaskViewModel.getDesc());

        //取消订单后，需要将redis中的zset中的接单数-1
        updateTaskZset(task, -1);

        return updateById(task);
    }

    /**
     * 完成工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean complete(Long id) {
        TaskEntity task = getById(id);
        //1.如果工单状态是已取消或已完成，抛出异常
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL || task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH) {
            throw new LogicException("工单状态为已取消或已完成");
        }

        //2.修改工单状态为完成
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        updateById(task);

        //3.完成运维工单后，要根据工单类型更改售货机状态
        //3.1 投放工单完成后需要将售货机状态更改为运营状态，撤机工单完成后将售货机状态更改为撤机状态，维修工单则不做任何处理
        if (task.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY || task.getProductTypeId() == VMSystem.TASK_TYPE_REVOKE) {
            //封装协议并发送
            noticeVMServiceStatus(task);
        }
        //3.2 完成补货工单后，要更新售货机库存
        if (task.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            noticeVMServiceSupply(task);
        }

        return true;
    }

    /**
     * 封装协议并发送消息（补货工单）
     *
     * @param task
     */
    private void noticeVMServiceSupply(TaskEntity task) {
        //1.根据工单id查询到工单详情
        LambdaQueryWrapper<TaskDetailsEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskDetailsEntity::getTaskId, task.getTaskId());
        List<TaskDetailsEntity> detailsEntities = taskDetailsService.list(wrapper);

        //2.封装协议
        SupplyContract supplyContract = new SupplyContract();
        //售货机编号
        supplyContract.setInnerCode(task.getInnerCode());
        List<SupplyChannel> supplyChannels = new ArrayList<>();

        detailsEntities.forEach(d -> {
            SupplyChannel supplyChannel = new SupplyChannel();
            //货道编号
            supplyChannel.setChannelId(d.getChannelCode());
            //补货数量
            supplyChannel.setCapacity(d.getExpectCapacity());
            supplyChannels.add(supplyChannel);
        });
        //补货数据
        supplyContract.setSupplyData(supplyChannels);

        //3.发送消息到emq
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 2, supplyContract);
        } catch (Exception e) {
            log.info("发送补货工单完成协议出错");
            throw new LogicException("发送补货工单完成协议出错");
        }

    }

    /**
     * 封装协议并发送消息（运维工单）
     *
     * @param task
     */
    private void noticeVMServiceStatus(TaskEntity task) {
        //封装协议
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setInnerCode(task.getInnerCode());
        taskCompleteContract.setTaskType(task.getProductTypeId());
        //发送消息到emq
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, taskCompleteContract);
        } catch (Exception e) {
            log.info("发送运维工单协议出错");
            throw new LogicException("发送运维工单协议出错");
        }
    }

    /**
     * 检查同一台设备是否有未完成工单
     *
     * @param taskViewModel
     */
    private void checkTask(TaskViewModel taskViewModel) throws LogicException {
        LambdaQueryWrapper<TaskEntity> wrapper = new LambdaQueryWrapper<>();
        //按照售货机编号和工单类型查询
        wrapper.select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, taskViewModel.getInnerCode())
                .eq(TaskEntity::getProductTypeId, taskViewModel.getProductType())
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);

        int count = count(wrapper);
        if (count > 0) {
            throw new LogicException("该机器有未完成的同类型工单");
        }
    }

    /**
     * 检验售货机状态
     *
     * @param taskViewModel
     */
    private void checkVMStatus(TaskViewModel taskViewModel) {

        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        if (vmInfo == null) {
            throw new LogicException("设备校验失败");
        }
        //如果是投放工单，状态为运营，抛出异常
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运营");
        }
        //如果是补货工单，状态不是运营状态，抛出异常
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }
        //如果是撤机工单，状态不是运营状态，抛出异常
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_REVOKE && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }
    }

    /**
     * 通过redis获取工单编号
     *
     * @return
     */
    private String getTaskCode() {
        //日期字符串
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = "lkd.task.code" + date;
        Object obj = redisTemplate.opsForValue().get(key);

        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }

        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }

    /**
     * 获取同一天内工单用户获取最少的人
     *
     * @param regionId
     * @param isRepair 是否是运维工单
     * @return
     */
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode = "1002"; //默认是运营人员
        if (isRepair) {
            roleCode = "1003";
        }

        //key值：固定前缀+日期+区域+工单类别（运营+运维）
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + regionId + "." + roleCode;

        //从zset中获取最少工单的用户
        Set<Object> set = redisTemplate.opsForZSet().range(key, 0, 1);
        if (set == null || set.isEmpty()) {
            throw new LogicException("当前区域尚无相关人员");
        }

        return (Integer) set.stream().collect(Collectors.toList()).get(0);
    }
}
